package org.hgf.testrabbitmq.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author 何国发
 * @version 1.0.0
 * @date 2022/9/13 10:22
 */
@Slf4j
public class ConvertUtils {

    /**
     * 对象转字节数组
     *
     * @param obj   要转的对象
     * @return byte[]
     * @author 何国发
     * @date 2022/9/13 10:22
     */
    public static byte[] objectToByte(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bo = null;
        ObjectOutputStream oo = null;
        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);

            bytes = bo.toByteArray();
        } catch (Exception e) {
            log.info("【BeanToByteUtil】translation->{}:e->{}" , e.getMessage(),e);
            e.printStackTrace();
        } finally {
            if (bo != null)
            {
                try {
                    bo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (oo != null)
            {
                try {
                    oo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }

    /**
     * 字节数组转对象
     *
     * @param bytes 要转换的字节数组
     * @return java.lang.Object
     * @author 何国发
     * @date 2022/9/13 10:26
     */
    public static Object byteToObject(byte[] bytes) {
        Object obj = null;
        ByteArrayInputStream bi = null;
        ObjectInputStream oi = null;
        try {
            // bytearray to object
            bi = new ByteArrayInputStream(bytes);
            oi = new ObjectInputStream(bi);

            obj = oi.readObject();

        } catch (Exception e) {
            log.info("【BeanToByteUtil】translation->{}，e->{}" , e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (bi != null)
            {
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (oi != null)
            {
                try {
                    oi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }

}
